<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动名称" prop="eventName">
        <el-input
          v-model="queryParams.eventName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申请人" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入申请人用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择所属分类" clearable filterable>
          <el-option
            v-for="opt in categoryOptions"
            :key="opt.id"
            :label="opt.name"
            :value="opt.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属地区" prop="regionId">
        <el-select v-model="queryParams.regionId" placeholder="请选择所属地区" clearable filterable>
          <el-option
            v-for="opt in regionOptions"
            :key="opt.id"
            :label="opt.name"
            :value="opt.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动地址" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入活动地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主办方" prop="organizer">
        <el-input
          v-model="queryParams.organizer"
          placeholder="请输入主办方"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请状态" prop="applyStatus">
        <el-select v-model="queryParams.applyStatus" placeholder="请选择申请状态" clearable>
          <el-option
            v-for="dict in ich_event_apply_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['management:EventApplication:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleAudit"
          v-hasPermi="['management:EventApplication:audit']"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['management:EventApplication:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['management:EventApplication:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="EventApplicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template #default="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动名称" align="center" prop="eventName" />
      
      <el-table-column label="申请人" align="center" prop="username">
        <template #default="scope">
          <span>{{ scope.row.username || scope.row.userid }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属分类" align="center" prop="categoryId">
        <template #default="scope">
          <span>{{ getCategoryName(scope.row.categoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属地区" align="center" prop="regionId">
        <template #default="scope">
          <span>{{ getRegionName(scope.row.regionId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动地址" align="center" prop="location" />
      <el-table-column label="主办方" align="center" prop="organizer" />
      <el-table-column label="活动简介" align="center" prop="introduction" show-overflow-tooltip />
      <el-table-column label="封面图片" align="center" prop="coverImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.coverImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="applyStatus">
        <template #default="scope">
          <dict-tag :options="ich_event_apply_status" :value="scope.row.applyStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审核备注" align="center" prop="reviewRemark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleAudit(scope.row)" v-hasPermi="['management:EventApplication:audit']">审核</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['management:EventApplication:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改申请管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="EventApplicationRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog :title="title" v-model="auditOpen" width="500px" append-to-body>
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核状态" prop="applyStatus">
          <el-select v-model="auditForm.applyStatus" placeholder="请选择审核状态">
            <el-option
              v-for="dict in ich_event_apply_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核备注" prop="reviewRemark">
          <el-input
            type="textarea"
            v-model="auditForm.reviewRemark"
            placeholder="请输入审核备注"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EventApplication">
import { listEventApplication, getEventApplication, delEventApplication, addEventApplication, updateEventApplication, auditEventApplication } from "@/api/management/EventApplication"
import { listEventCategory } from "@/api/management/EventCategory"
import { listEventRegion } from "@/api/management/EventRegion"

const { proxy } = getCurrentInstance()
const { ich_event_apply_status } = proxy.useDict('ich_event_apply_status')

const EventApplicationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const selectedRows = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const auditOpen = ref(false)
const auditForm = ref({
  id: null,
  applyStatus: null,
  reviewRemark: ''
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    eventName: null,
    startTime: null,
    username: null,
    categoryId: null,
    regionId: null,
    location: null,
    organizer: null,
    applyStatus: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

const categoryOptions = ref([])
const regionOptions = ref([])

function fetchCategoryOptions() {
  // 拉取分类选项，数量取较大值以覆盖
  listEventCategory({ pageNum: 1, pageSize: 1000 }).then(res => {
    categoryOptions.value = res.rows || []
  })
}

/** 审核按钮操作 */
function handleAudit(row) {
  const _id = (row && row.id) ? row.id : ids.value[0]
  if (!_id) {
    proxy.$modal.msgWarning("请先选择一条数据进行审核")
    return
  }
  // 优先使用表格当前行的状态与备注进行预填
  if (row && row.id) {
    auditForm.value = {
      id: row.id,
      applyStatus: row.applyStatus == null ? null : String(row.applyStatus),
      reviewRemark: row.reviewRemark ?? ''
    }
    auditOpen.value = true
    title.value = "审核申请"
  } else {
    // 无行数据时，按选中ID拉取详情进行预填
    getEventApplication(_id).then(response => {
      const data = response.data || {}
      auditForm.value = {
        id: _id,
        applyStatus: data.applyStatus == null ? null : String(data.applyStatus),
        reviewRemark: data.reviewRemark ?? ''
      }
      auditOpen.value = true
      title.value = "审核申请"
    })
  }
}

/** 审核提交 */
function submitAudit() {
  if (!auditForm.value.id) {
    proxy.$modal.msgWarning("缺少审核ID")
    return
  }
  if (auditForm.value.applyStatus === null) {
    proxy.$modal.msgWarning("请选择审核状态")
    return
  }
  const payload = {
    ...auditForm.value,
    applyStatus: auditForm.value.applyStatus == null ? null : Number(auditForm.value.applyStatus)
  }
  auditEventApplication(payload).then(() => {
    proxy.$modal.msgSuccess("审核成功")
    auditOpen.value = false
    getList()
  })
}

function cancelAudit() {
  auditOpen.value = false
}

function fetchRegionOptions() {
  listEventRegion({ pageNum: 1, pageSize: 1000 }).then(res => {
    regionOptions.value = res.rows || []
  })
}

function getCategoryName(id) {
  const item = categoryOptions.value.find(x => x.id === id)
  return item ? item.name : id
}

function getRegionName(id) {
  const item = regionOptions.value.find(x => x.id === id)
  return item ? item.name : id
}

// 初始化选项
fetchCategoryOptions()
fetchRegionOptions()

/** 查询申请管理列表 */
function getList() {
  loading.value = true
  listEventApplication(queryParams.value).then(response => {
    EventApplicationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    eventName: null,
    startTime: null,
    endTime: null,
    userid: null,
    categoryId: null,
    regionId: null,
    location: null,
    organizer: null,
    introduction: null,
    coverImage: null,
    detailContent: null,
    detailImages: null,
    applyStatus: null,
    reviewRemark: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("EventApplicationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedRows.value = selection
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加申请管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getEventApplication(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改申请管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["EventApplicationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateEventApplication(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addEventApplication(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const start = (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  let seqText = ''
  let _ids

  if (row && row.id) {
    const idx = EventApplicationList.value.findIndex(r => r.id === row.id)
    const seq = start + idx + 1
    seqText = String(seq)
    _ids = row.id
  } else {
    const seqs = selectedRows.value.map(r => {
      const idx = EventApplicationList.value.findIndex(rr => rr.id === r.id)
      return start + idx + 1
    })
    seqText = seqs.join('、')
    _ids = ids.value
  }

  proxy.$modal.confirm('是否确认删除序号为"' + seqText + '"的数据项？').then(function() {
    return delEventApplication(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('management/EventApplication/export', {
    ...queryParams.value
  }, `EventApplication_${new Date().getTime()}.xlsx`)
}

getList()
</script>
